package com.zxt.content.common.utils;

import lombok.NoArgsConstructor;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.util.*;

@NoArgsConstructor
public class ZXTBeanUtils {

    //定义BeanCopier
    static final Map<String, BeanCopier> BEAN_COPIERS = new HashMap();

    /**
     * 将
     * @param source
     * @param target
     */
    public static void beanCopy(Object source, Object target) {
        if (source != null && target != null) {

            //获取map的key
            String key = genKey(source, target);
            BeanCopier copier = null;

            //如果BEAN_COPIERS缓存不存在对应转换类，创建出一个对应的转换类型进行存储
            if (!BEAN_COPIERS.containsKey(key)) {
                copier = BeanCopier.create(source.getClass(), target.getClass(), false);
                BEAN_COPIERS.put(key, copier);
            } else {
                //如果存在的话直接取BEAN_COPIERS缓存里的
                copier = (BeanCopier)BEAN_COPIERS.get(key);
            }

            //进行值的深拷贝
            copier.copy(source, target, (Converter)null);
        }
    }

    public static <S, T> T beanCopy(S source, Class<T> targetClazz) {
        if (source == null) {
            return null;
        } else {
            Object target = null;

            try {
                target = targetClazz.newInstance();
            } catch (InstantiationException var4) {
                var4.printStackTrace();
            } catch (IllegalAccessException var5) {
                var5.printStackTrace();
            }

            beanCopy(source, target);
            return (T) target;
        }
    }

    /**
     *
     * @param origLst 转换的List集合
     * @param destClz 需要转换的类型
     * @param <S>
     * @param <T> 返回的类型
     * @return
     */
    public static <S, T> List<T> beanCopy(List<S> origLst, Class<T> destClz) {
        ArrayList<T> destLst = new ArrayList();
        if (ZXTCollectionsUtil.isEmpty(origLst)) {
            return destLst;
        } else {
            Iterator var3 = origLst.iterator();

            while(var3.hasNext()) {
                S orig = (S) var3.next();
                T dest = beanCopy(orig, destClz);
                destLst.add(dest);
            }

            return destLst;
        }
    }

    private static String genKey(Object source, Object target) {
        //通过原类型的类名和转换类型的类名生成key
        return source.getClass().getName() + target.getClass().getName();
    }

/*    public static <S, T> QueryResultVO<T> pageToQueryResultVO(Page<S> page, Class<T> targetClazz) {
        if (page == null) {
            return null;
        } else {
            QueryResultVO<T> queryResultVO = new QueryResultVO();
            queryResultVO.setPageNo(page.getCurrent());
            queryResultVO.setPageSize(page.getSize());
            queryResultVO.setTotalPages(page.getPages());
            queryResultVO.setTotalRecords(page.getTotal());
            return queryResultVO;
        }
    }*/
}
